require "wondercap/lib/utils/logging"
require "wondercap/lib/utils/syscmd"

module ::Wondercap
module Deployment
module NameFilters
    
  class SvnHookFilter
    include Logging, Syscmd
    
    def get_paths(base_config)
      repository = base_config.fetch(:repository).chomp("/")
      revision = base_config.fetch :revision
      svn_bin = base_config.fetch :svn_bin, "svn"

      svn_log_command = "'#{svn_bin}' log '#{repository}' -v -r '#{revision}' 2>&1"
      output = syscmd_output(svn_log_command)

      output.split($/).inject([]) do |paths, line|
        if (line =~ /Changed paths:/)...(line =~ /^$/)
          paths << "#{repository}#{$&}" if line =~ %r(/.*$)
        end
        paths
      end 
    end
    private :get_paths

    def call(names, base_config)
      paths = get_paths(base_config)
      
      names.delete_if do |name|
        config = base_config.mc.get_configuration(name)
        next true unless config.fetch(:scm_type, nil) == :subversion
         
        not paths.find do |path|
          path =~ /^#{Regexp.escape config.repository}([^[:alnum:]]|$)/
        end
      end
      if base_config.fetch(:force_head, false)
        names.each do |name|
          base_config.mc.get_configuration(name).use(:head).for(:revision)
        end
      end
      names
    end
    
  end
  
end
end
end

define_name_filter :svn_hook, Wondercap::Deployment::NameFilters::SvnHookFilter.new
